package com.example.farmer.Database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.farmer.Entity.ProductPost;

import java.util.ArrayList;
import java.util.List;

public class ProductPublishDatabase extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "farmer_product.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "product_posts";

    // Columns
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_IMAGE_URI = "image_uri";
    private static final String COLUMN_TITLE = "title";
    private static final String COLUMN_PRODUCT_TYPE = "product_type";
    private static final String COLUMN_PRICES = "prices";
    private static final String COLUMN_FREIGHT = "freight";
    private static final String COLUMN_SHIP_ADDRESS = "ship_address";
    private static final String COLUMN_PUSH_TYPE = "push_type";
    private static final String COLUMN_NUMBER = "userNumber";

    // Ordered Columns array for query
    private static final String[] COLUMN_NAMES = {
            COLUMN_ID, COLUMN_IMAGE_URI, COLUMN_TITLE, COLUMN_PRODUCT_TYPE,
            COLUMN_PRICES, COLUMN_FREIGHT, COLUMN_SHIP_ADDRESS, COLUMN_PUSH_TYPE, COLUMN_NUMBER
    };

    private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_IMAGE_URI + " TEXT,"
            + COLUMN_TITLE + " TEXT,"
            + COLUMN_PRODUCT_TYPE + " TEXT,"
            + COLUMN_PRICES + " TEXT,"
            + COLUMN_FREIGHT + " TEXT,"
            + COLUMN_SHIP_ADDRESS + " TEXT,"
            + COLUMN_PUSH_TYPE + " TEXT,"
            + COLUMN_NUMBER + " TEXT"
            + ")";

    private static ProductPublishDatabase instance;

    public ProductPublishDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static synchronized ProductPublishDatabase getInstance(Context context) {
        if (instance == null) {
            instance = new ProductPublishDatabase(context.getApplicationContext());
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    // Common query method with consistent ordering
    private Cursor queryDatabase(SQLiteDatabase db, String selection, String[] selectionArgs, String[] columns) {
        return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null);
    }

    // Specific query methods using the common query method
    public List<ProductPost> getPostsByPushType(String pushType) {
        return queryAndCreateList(COLUMN_PUSH_TYPE + " = ?", new String[]{pushType});
    }

    public List<ProductPost> getPostsByProductType(String productType) {
        return queryAndCreateList(COLUMN_PRODUCT_TYPE + " = ?", new String[]{productType});
    }

    private List<ProductPost> queryAndCreateList(String selection, String[] selectionArgs) {
        List<ProductPost> posts = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = queryDatabase(db, selection, selectionArgs, COLUMN_NAMES);
        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    posts.add(createProductPostFromCursor(cursor));
                }
            } finally {
                cursor.close();
            }
        }
        db.close();
        return posts;
    }

    public ProductPost getProductPostById(int productId) {
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_ID + " = ?";
        String[] selectionArgs = {String.valueOf(productId)};
        Cursor cursor = queryDatabase(db, selection, selectionArgs, COLUMN_NAMES);
        ProductPost post = null;
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    post = createProductPostFromCursor(cursor);
                }
            } finally {
                cursor.close();
            }
        }
        db.close();
        return post;
    }

    public ProductPost getPostsByIdAndUserNumber(int productId, String userNumber) {
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_ID + " = ? AND " + COLUMN_NUMBER + " = ?";
        String[] selectionArgs = {String.valueOf(productId), userNumber};
        Cursor cursor = queryDatabase(db, selection, selectionArgs, COLUMN_NAMES);
        ProductPost post = null;
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    post = createProductPostFromCursor(cursor);
                }
            } finally {
                cursor.close();
            }
        }
        db.close();
        return post;
    }

    // Common method to create a ProductPost object from a cursor
    @SuppressLint("Range")
    private ProductPost createProductPostFromCursor(Cursor cursor) {
        return new ProductPost(
                cursor.getInt(cursor.getColumnIndex(COLUMN_ID)),
                cursor.getString(cursor.getColumnIndex(COLUMN_IMAGE_URI)),
                cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)),
                cursor.getString(cursor.getColumnIndex(COLUMN_PRODUCT_TYPE)),
                cursor.getDouble(cursor.getColumnIndex(COLUMN_PRICES)),
                cursor.getDouble(cursor.getColumnIndex(COLUMN_FREIGHT)),
                cursor.getString(cursor.getColumnIndex(COLUMN_SHIP_ADDRESS)),
                cursor.getString(cursor.getColumnIndex(COLUMN_PUSH_TYPE)),
                cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER))
        );
    }

    // Insert method
    public long insertPost( String imageUri,String title, String productType, String prices, String freight,
                           String shipAddress,  String pushType,String userNumber) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_IMAGE_URI, imageUri);
        values.put(COLUMN_TITLE, title);
        values.put(COLUMN_PRODUCT_TYPE, productType);
        values.put(COLUMN_PRICES, prices);
        values.put(COLUMN_FREIGHT, freight);
        values.put(COLUMN_SHIP_ADDRESS, shipAddress);
        values.put(COLUMN_PUSH_TYPE, pushType);
        values.put(COLUMN_NUMBER, userNumber);
        long result = db.insert(TABLE_NAME, null, values);
        return result;
    }

    // Delete method
    public void deletePost(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
        db.close();
    }
}